package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.dto.DishDto;

import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {
    @Autowired(required = false)
    private DishMapper dishMapper;
    @Autowired(required = false)
    private DishFlavorMapper dishFlavorMapper;
    @Autowired(required = false)
    private CategoryMapper categoryMapper;
    @Autowired(required = false)
    private RedisTemplate redisTemplate;

    @Transactional
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //1.补全菜品信息
        dishDto.setStatus(1); //启用禁用
        dishDto.setSort(0);
        //2.保存菜品
        dishMapper.save(dishDto);
        //获取
        final Long dishId = dishDto.getId();
        //3.获取所有的口味信;补全dish_id; 保存口味信息;
        //获取口味信息
        //传统写法
        List<DishFlavor> dishFlavorList = dishDto.getFlavors();
       /*for(DishFlavor dishFlavor:dishFlavorList){
            dishFlavor.setDishId(dishId);
            dishFlavor.setUpdateTime(LocalDateTime.now());
            dishFlavor.setCreateTime(LocalDateTime.now());
            dishFlavor.setCreateUser(dishDto.getCreateUser());
            dishFlavor.setUpdateUser(dishDto.getUpdateUser());
        }*/
        dishFlavorList.stream().map((dishFlavor -> {
            dishFlavor.setDishId(dishId);
            dishFlavor.setUpdateTime(LocalDateTime.now());
            dishFlavor.setCreateTime(LocalDateTime.now());
            dishFlavor.setCreateUser(dishDto.getCreateUser());
            dishFlavor.setUpdateUser(dishDto.getUpdateUser());
            return dishFlavor;
        })).collect(Collectors.toList());
        //批量保存口味信息
        dishFlavorMapper.saveBatch(dishFlavorList);
        //5. 删除缓存
        final Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
    }

    @Override
    public Page<DishDto> page(Integer page, Integer pageSize, String name) {
        //设置当前页和页面大小
        PageHelper.startPage(page, pageSize);
        //获取数据,获取到 List<Dish>
        List<Dish> dishList = dishMapper.findByName(name);
        //构建pageIfo对象那个
        PageInfo<Dish> pageInfo = new PageInfo<>(dishList);
        final ArrayList<DishDto> dishDtoList = new ArrayList<>();
        List<DishDto> collect = pageInfo.getList().stream().map((dish -> {
            final DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            Category category = categoryMapper.findById(dish.getCategoryId());
            dishDto.setCategoryName(category.getName());
            return dishDto;

        })).collect(Collectors.toList());
        Page<DishDto> pageResult = new Page<>(collect, pageInfo.getTotal(), pageSize, page);
        return pageResult;


    }

    /**
     * 根据id查询菜品和菜的口味
     *
     * @param id 菜品的id
     * @return
     */
    @Override
    public DishDto findById(long id) {
        //根据id查找菜品
        Dish dish = dishMapper.findById(id);
        //根据id查找相应菜品的口味
        List<DishFlavor> dishFlavorList = dishFlavorMapper.findById(id);
        //创建DishDto ,把菜品,口味信息封装到DishDat中
        final DishDto dishDto = new DishDto();
        //属性拷贝
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(dishFlavorList);
        return dishDto;

    }

    /**
     * 根据修改商品
     *
     * @param dishDto 页面传递过来对的参数包含菜品和口味
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //1. 补全修改时间
        dishDto.setUpdateTime(LocalDateTime.now());
        //1.修改菜品
        dishMapper.updateById(dishDto);
        //2. 根据菜品删除该菜品的所有的口味
        dishFlavorMapper.deleteByDishId(dishDto.getId());
        //3. 补全口味信息,然后重新插入
        final List<DishFlavor> flavors = dishDto.getFlavors();
        List<DishFlavor> dishFlavorList = flavors.stream().map((dishFlavor -> {
            dishFlavor.setDishId(dishDto.getId());
            dishFlavor.setUpdateTime(LocalDateTime.now());
            dishFlavor.setCreateTime(LocalDateTime.now());
            dishFlavor.setCreateUser(dishDto.getCreateUser());
            dishFlavor.setUpdateUser(dishDto.getUpdateUser());
            return dishFlavor;
        })).collect(Collectors.toList());
        //4.批量保存口味信息
        dishFlavorMapper.saveBatch(dishFlavorList);
        //5. 清除缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
    }

    /**
     * 根据条件查询对应的菜品管理
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishDto> findByCategoryId(Long categoryId, Integer status) {
        List<DishDto> dishDtoList = null;
        String key = "dish_" + categoryId;
        //从redis中取出
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList == null) {
            List<Dish> dishList = dishMapper.findByCategoryId(categoryId, status);
            dishDtoList = dishList.stream().map(dish -> {
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(dish, dishDto);
                //查看该菜品的口味信息
                List<DishFlavor> dishFlavorList = dishFlavorMapper.findByDishId(dish.getId());
                dishDto.setFlavors(dishFlavorList);
                //类别信息
                Category category = categoryMapper.findById(dish.getCategoryId());
                dishDto.setCategoryName(category.getName());

                return dishDto;
            }).collect(Collectors.toList());
              //重新存储在缓存里
            redisTemplate.opsForValue().set(key,dishDtoList);}
            return dishDtoList;
        }

        /**
         * 删除菜品(可批量)
         *
         * @param ids
         * @return
         */
        @Override
        public void deleteByIds (List < Long > ids) {
            //1. 判断里面是否有在售状态,在售不可删除,查询是否存在在售状态
            Long count = dishMapper.qureyDishWithStatus(ids);
            if (count > 0) {
                //若不能删除则抛出异常
                throw new ClassCastException("存在在售菜品,无法删除");
            }
            //2. 若删除套餐都是停售状态,则可直接删除
            dishMapper.deleteByIds(ids);
        }

        /**
         * 批量停售起售状态
         *
         * @param ids
         * @param status
         */
        @Override
        public void updateStatus (List < Long > ids, Integer status){

            dishMapper.updateStatus(ids, status);
        }}
